package com.rd.sys.common.threadpool.block;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import baseproj.component.log.LoggerAdapter;
import baseproj.component.log.LoggerService;

public class SimpleThreadPool {
    private static LoggerService logger = LoggerAdapter.getLoggerService(SimpleThreadPool.class);

    /**
     * 线程池维护线程的最少数量
     */
    private final int core_pool_size;

    /**
     * 线程池维护线程的最大数量
     */
    private final int max_pool_size;

    /**
     * 线程池维护线程所允许的空闲时间(秒)
     */
    private final long keepalive_time;

    /**
     * 线程池所使用的缓冲队列大小
     */
    private final int queue_capacity;

    /**
     * 线程池所使用的缓冲队列
     */
    private BlockingQueue<Runnable> workQueue = null;

    private static TimeUnit TIME_UNIT = TimeUnit.SECONDS;

    /**
     * ThreadPoolExecutor.AbortPolicy():抛出RejectedExecutionException
     */
    private static RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();

    private ThreadPoolExecutor threadPool = null;

    public SimpleThreadPool(int core_pool_size, int max_pool_size, int queue_capacity, long keepalive_time) {
        this.core_pool_size = core_pool_size;
        this.max_pool_size = max_pool_size;
        this.queue_capacity = queue_capacity;
        this.keepalive_time = keepalive_time;
        workQueue = new ArrayBlockingQueue<Runnable>(this.queue_capacity);

        threadPool = new ThreadPoolExecutor(this.core_pool_size, this.max_pool_size, this.keepalive_time, TIME_UNIT,
                workQueue, rejectedExecutionHandler);
    }

    public boolean execute(Runnable task) {
        try {
            threadPool.execute(task);
        } catch (RejectedExecutionException e) {
            logger.error("the work queue is full!", e);
            return false;
        } catch (Exception e) {
            logger.error("other exception in threadpool!", e);
            return false;
        }
        return true;

    }
}
